package org.schat.sockets;

import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

public class MessageDecoder implements Decoder.Text<ChatMessage> {

	Gson gson;

	@Override
	public void destroy() {
		gson = null;
	}

	@Override
	public void init(EndpointConfig config) {
		gson = new Gson();
	}

	@Override
	public ChatMessage decode(String msg) throws DecodeException {
		if (msg != null && !"".equals(msg)) {
			try {
				return gson.fromJson(msg, ChatMessage.class);
			} catch (JsonSyntaxException e) {
				//do nothing
			}
		}
		return null;
	}

	@Override
	public boolean willDecode(String msg) {
		return true;
	}

}
